package com.example.sso.clientA.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sso.clientA.dao.SysPermissionDao;
import com.example.sso.clientA.dao.SysRoleAccountDao;
import com.example.sso.clientA.entity.SysPermission;
import com.example.sso.clientA.entity.SysRoleAccount;
import com.example.sso.clientA.service.SysAccountService;
import com.yky.service.sys.SysPermissionService;
import com.yky.service.sys.SysRoleAccountService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * (SysRoleAccount)表服务实现类
 *
 * @author makejava
 * @since 2024-02-21 09:57:45
 */
@Service("sysRoleAccountService")
public class SysRoleAccountServiceImpl implements SysRoleAccountService {
    @Resource
    private SysPermissionDao sysPermissionDao;
    @Resource
    private SysRoleAccountDao sysRoleAccountDao;

    @Override
    public List<String> getAccountRoleList(String accountId) {
        List<String> result = new ArrayList<>();
        List<SysRoleAccount> list = sysRoleAccountDao.listByAccountId(accountId);
        if (list == null || list.size() <= 0){
            return result;
        }
        return list.stream().map(SysRoleAccount::getRoleId).distinct().collect(Collectors.toList());
    }

    @Override
    public Map<String, List<String>> getUrlMappingRoles() {
        Map<String, List<String>> result = new HashMap<>();
        List<SysPermission> list = sysPermissionDao.list();
        if (list == null || list.size() <= 0){
            return result;
        }
        Map<String, List<SysPermission>> collect = list.stream().collect(Collectors.groupingBy(SysPermission::getPermissionUrl));
        Set<Map.Entry<String, List<SysPermission>>> entries = collect.entrySet();
        for (Map.Entry<String, List<SysPermission>> entry : entries){
            String url = entry.getKey();
            List<SysPermission> values = entry.getValue();
            if (values == null || values.size() <= 0){
                continue;
            }
            List<String> accounts = values.stream().map(s -> s.getAccountId()).distinct().collect(Collectors.toList());
            List<SysRoleAccount> sysRoleAccounts = sysRoleAccountDao.listByAccountIds(accounts);
            if (sysRoleAccounts == null || sysRoleAccounts.size() <= 0){
                continue;
            }
            List<String> roleIds = sysRoleAccounts.stream().map(s -> s.getRoleId()).distinct().collect(Collectors.toList());
            result.put(url, roleIds);
        }
        return result;
    }
}

